package cn.edu.scau.controller;

import cn.edu.scau.bean.ResultBean;
import cn.edu.scau.bean.UserResultBean;
import cn.edu.scau.config.Audience;
import cn.edu.scau.entity.Manager;
import cn.edu.scau.entity.Nurse;
import cn.edu.scau.service.ManagerService;
import cn.edu.scau.service.NurseService;
import cn.edu.scau.util.JWTTokenUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.ParseException;
import java.util.Calendar;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

@Api(tags = "用户信息控制器")
@RestController
//@Controller
public class ManagerController {
    @Autowired
    private ManagerService managerService;
    @Autowired
    private NurseService nurseService;
    @Autowired
    private Audience audience;
    /**
     * 显示所有用户信息页面
     * @return
     */
    @ApiOperation(value = "显示所有信息页面:数据存储在hospital中")
    @GetMapping(value = "list")
    //@ResponseBody
    public ResultBean list(@RequestParam(value = "pageNum",defaultValue = "1")int pageNum,
                           @RequestParam(value = "pageSize",defaultValue = "5")int pageSize){
        PageHelper.startPage(pageNum, pageSize);
        List<Manager> managers = managerService.selectAll();
        PageInfo<Manager> pageInfo = new PageInfo<Manager>(managers);
        //只显示有效标志位为true的用户

        ResultBean r = new ResultBean(200,true,"查询所有部门信息成功",pageInfo);

        return r;
    }

    /**
     *  登录验证
     * @param manager
     * @param bindingResult
     * @param session
     * @return
     */
    @PostMapping(value = "checklogin")
   // @ResponseBody
    public UserResultBean checklogin(@Validated Manager manager, BindingResult bindingResult, HttpSession session) {
        UserResultBean r = null;
        if (bindingResult.hasErrors()) {
            //方法一：将无法通过数据校验的信息，合并成一个字符串，返回给前端
            StringBuffer msg = new StringBuffer();
            for (FieldError f : bindingResult.getFieldErrors()
            ) {
                msg.append(f.getField() + ":" + f.getDefaultMessage() + "\n");
            }
            r = new UserResultBean(5006, false, msg.toString(), null,null);

            return r;
        }
        Manager targetManager = managerService.login(manager.getUserAccount(),manager.getUserPassword());
        manager.setUserPassword("************");
        if(null!=targetManager&&targetManager.getUserUseflag()!=false){
            //session方案
//            r = new ResultBean(200,true,"登陆成功","");
//            session.setAttribute("management",targetManagement);
            //JWT方案
            String token = JWTTokenUtil.createJWT(""+targetManager.getUserId(),targetManager.getUserAccount(),audience);
            r = new UserResultBean(200,true,targetManager.getUserAccount(),token,targetManager.getUserPosition());

        }

        else{
//            r = new ResultBean(5009,false,"登录名称或密码有可能错误，登陆失败","");
//            session.removeAttribute("management");
            r = new UserResultBean(5007,false,"登录名称或密码有可能错误,或者账号已过期",null,null);
        }
        return r;
    }
    /**
     * 注销并返回登陆页面
     * @return
     */
    @GetMapping(value = "exit")
   // @ResponseBody
    public ResultBean exit(HttpServletRequest request) {
        //重新生成JWT
//        final String token = request.getHeader(JWTTokenUtil.AUTH_HEAD_KEY);
//        String userid = JWTTokenUtil.getUserId(token,audience.getBase64Secret());
//        String username = JWTTokenUtil.getUserName(token,audience.getBase64Secret());
        return new ResultBean(200,true,"注销成功",null);
    }

    /**
     * 根据用户账号查询用户信息
     * @param userAccount
     * @return
     */
    @ApiOperation(value = "根据用户账号查询用户信息")
    @ApiImplicitParam(paramType = "path" ,name = "userAccount" , value = "账号",dataType = "String")
    @ApiResponse(code = 200,message = "返回updatedepartment页面,数据存储在office中")
    @GetMapping(value = "/{userAccount}")
//    @ResponseBody
    public ResultBean detail(@PathVariable("userAccount") String userAccount){
        Manager manager = managerService.selectByUserAccount(userAccount);
        ResultBean r = new ResultBean(200, true, "查询成功", manager);
        //查不到
        if(manager==null) {
            r = new ResultBean(5008, false, "查询失败", null);
        }
        return r;
    }
    /**
     * 显示所根据编号模糊查询
     * 基于前后端分离
     * @param
     * @return
     */
    @ApiOperation(value = "根据编号模糊查询,数据存储在hospital中")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(paramType = "query" ,name = "userId" , value = "编号",dataType = "int"),
    })
    @GetMapping(value = "/find")
//    @ResponseBody
    public ResultBean find(@RequestParam(value = "pageNum",defaultValue = "1")int pageNum,
                           @RequestParam(value = "pageSize",defaultValue = "5")int pageSize
            ,Integer userId){
        PageHelper.startPage(pageNum, pageSize);
        List<Manager> managers = managerService.findById(userId);
        PageInfo<Manager> pageInfo = new PageInfo<Manager>(managers);
        ResultBean r = new ResultBean(200,true,"查询所有部门信息成功",pageInfo);
        return r;
    }
    /**
     * 修改部门信息
     * @param userAccount

     * @return
     * @throws ParseException
     */
    @PutMapping(value = "/update/{userAccount}")
//    @ResponseBody
    public ResultBean update(@PathVariable("userAccount") String userAccount,@Validated Manager manager, BindingResult bindingResult) {
        ResultBean r = null;
        if(bindingResult.hasErrors()){
            //方法一：将无法通过数据校验的信息，合并成一个字符串，返回给前端
            StringBuffer msg = new StringBuffer();
            for (FieldError f:bindingResult.getFieldErrors()
            ) {
                msg.append(f.getField()+":"+f.getDefaultMessage()+"\n");
            }
            r = new ResultBean(5006,false,msg.toString(),null);
            //方法二：将所有无法通过数据校验的信息集合，直接返回给前端，让前端自行处理
            // r = new ResultBean(5004,false,"部门赋值失败",bindingResult.getFieldErrors());
            return r;
        }
        boolean flag = managerService.updateByUserAccountSelective(manager);
        if(flag){
            r =new ResultBean(200,true,"修改成功",null);
        }else
        {
            r =new ResultBean(5005,false,"修改失败",null);
        }
        return r;
    }
    /**
     * 改变标志位达到删除效果
     * @param userAccount

     * @return
     * @throws ParseException
     */
    @PutMapping(value = "/fakeDelete/{userAccount}")
//    @ResponseBody
    public ResultBean fakeDelete(@PathVariable("userAccount") String userAccount) {
        ResultBean r = null;
        Manager manager = managerService.selectByUserAccount(userAccount);
        //根据E-R图关系，若用户是护士，必须要先删除护士信息
        Nurse nurse = nurseService.selectByUserId(manager.getUserId());
        if(nurse!=null){
            nurse.setNurseuseflag(false);
            boolean flag1 = nurseService.updateByPrimaryKeySelective(nurse);
            if(!flag1)
            {
                r =new ResultBean(5005,false,"删除护士失败",null);
                return r;
            }
        }
        manager.setUserUseflag(false);
        boolean flag = managerService.updateByUserAccountSelective(manager);
        if(flag){
            r =new ResultBean(200,true,"删除成功",null);
        }else
        {
            r =new ResultBean(5005,false,"删除失败",null);
        }
        return r;
    }
    /**
     * 新增用户
     *
     * @return
     * @throws ParseException
     */
    @PostMapping(value = "/insert")
//    @ResponseBody
    public ResultBean insert(@Validated Manager manager, BindingResult bindingResult) {
        ResultBean r = null;
        if(bindingResult.hasErrors()){
            //方法一：将无法通过数据校验的信息，合并成一个字符串，返回给前端
            StringBuffer msg = new StringBuffer();
            for (FieldError f:bindingResult.getFieldErrors()
            ) {
                msg.append(f.getField()+":"+f.getDefaultMessage()+"\n");
            }
            r = new ResultBean(5006,false,msg.toString(),null);
            //方法二：将所有无法通过数据校验的信息集合，直接返回给前端，让前端自行处理
            // r = new ResultBean(5004,false,"部门赋值失败",bindingResult.getFieldErrors());
            return r;
        }
        Calendar calendar = Calendar.getInstance();
        manager.setUserUseflag(true);
        boolean flag = managerService.insert(manager);
        if(flag){
            String id = null;
            if(manager.getUserId().intValue()<10){id = "0"+manager.getUserId();}
            else{id=String.valueOf(manager.getUserId());}
            manager.setUserAccount(""+calendar.get(Calendar.YEAR)+manager.getUserPosition()+id);
            managerService.updateByPrimaryKey(manager);
            r =new ResultBean(200,true,"增加成功\n新增用户编号为"+manager.getUserId(),manager.getUserId());
        }else
        {
            r =new ResultBean(5005,false,"增加失败",null);
        }
        return r;
    }

}
